import json
import time
from flask import Flask, request, jsonify, Response
from flask_cors import CORS
from weather_integration.test_client import main_url
from LLM_Prompt.prompt_classify import classify
from LLM_Prompt.flow_extract import extract
from boat_nl2sql.boat_nl2sql_main import generate_analysis, analyze_sql_data
from Decryption.decryption import get_token, get_boat_flow_list
from boat_nl2sql.test_api import test_single_query

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app)  # 解决跨域问题


@app.route('/LLM', methods=['POST'])
def query_handler():
    global payload, cleaned_rows
    try:
        # 解析输入参数
        data = request.json
        question = data.get("question")
        if not question:
            return jsonify({"error": "缺少问题参数"}), 400

        # 分类问题类型
        start = time.time()
        classify_result = classify(question)
        classify_time = time.time() - start
        print(f"分类问题类型花费时间：{classify_time:.4f}秒")
        print(classify_result)

        # 处理不同类型的查询
        if classify_result in ["船舶流量", "统计问题", "其他"]:
            # 先提取关键信息再查询
            start = time.time()
            output_file, analysis = generate_analysis(question)
            generate_time = time.time() - start
            print(f"html图表+分析：{generate_time:.4f}秒")
            answer = analysis
            # 读取HTML文件内容
            try:
                with open(output_file, 'r', encoding='utf-8') as f:
                    html_content = f.read()
            except Exception as e:
                html_content = f"无法读取HTML文件: {str(e)}"

            payload = None
            cleaned_rows = None

        elif classify_result == "过船记录":
            # 先提取关键信息再查询
            start = time.time()
            extracted_info = extract(classify_result, question)
            extract_time = time.time() - start
            print(f"提取关键信息花费时间：{extract_time:.4f}秒")
            print(extracted_info)

            payload = extracted_info['extracted_data']

            # 获取密钥token
            token = get_token()
            print(token)

            # 调用港航 船舶流量检测记录 开发接口
            data = get_boat_flow_list(token, payload)
            print("data获取成功")

            # 数据处理
            # 遍历每条记录，剔除指定字段
            cleaned_rows = []
            for row in data["rows"]:
                # 创建新字典并排除不需要的字段
                cleaned_row = {
                    key: value for key, value in row.items()
                    if key not in ["imagePaths", "imageUrls", 'bayonetId', 'code', 'endPoint', 'locationMapx', 'locationMapy']
                }
                cleaned_rows.append(cleaned_row)

            print("获取到的数据字段清理成功")

            # start = time.time()
            # answer = analyze_sql_data(question, cleaned_rows)
            # analyze_time = time.time() - start
            # print(f"分析SQL数据花费时间：{analyze_time:.4f}秒")
            #
            # print("回答完毕")

            html_content = None

        else:
            return jsonify({"error": "未知查询类型"}), 400

        # 构造响应数据
        response_data = {
            "result": {
                "action_name": classify_result,
                "params": payload,
                "data": cleaned_rows,
                "question": question,
            },
            # "answer": answer,
            "html_content": html_content
        }

        # 使用jsonify并显式设置charset
        return Response(
            json.dumps(response_data, ensure_ascii=False),
            content_type='application/json; charset=utf-8'
        )

    except Exception as e:
    # 错误处理同样需要确保编码正确
        return Response(
            json.dumps({"error": str(e)}, ensure_ascii=False),
            content_type='application/json; charset=utf-8',
            status=500
        )


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)